package com.sunb2b.test;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sunb2b.web.form.PersonForm;

@Controller
public class SimpleFormController {

    @RequestMapping(value="/test/person", method=RequestMethod.GET)
    public String personform(Model model) {
        //form.setAge(13);
        PersonForm pf = new PersonForm();
        pf.setAge(14);
        model.addAttribute("personForm", pf);
        return "person";
    }
    
    @RequestMapping(value="/test/person", method=RequestMethod.POST)
    public String processSubmit(@Valid PersonForm personForm, BindingResult result, 
                                Model model, RedirectAttributes redirectAttrs) {
        if (result.hasErrors()) {
            return "person";
        }
        // Typically you would save to a db and clear the "form" attribute from the session 
        // via SessionStatus.setCompleted(). For the demo we leave it in the session.
        String message = "Form submitted successfully.  Bound " + personForm;
        // Success response handling
            // prepare model for rendering success message in this request
        model.addAttribute("message", message);
        // store a success message for rendering on the next request after redirect
        // redirect back to the form to render the success message along with newly bound values
        redirectAttrs.addFlashAttribute("message", message);
        return "person";
    }
    
}

